package com.hernie.user.service;


import com.hernie.user.mapper.UserMapper;
import com.hernie.user.pojo.User;
import com.hernie.user.util.HttpUtils;
import com.hernie.user.vo.UserVO;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

@Service("loginService")
public class LoginService {
    @Resource
    private UserMapper userMapper;

    public Map<String, Object> login(UserVO userVO, HttpSession session)  {
        Map<String, Object> map = new HashMap<>();
        User user = userMapper.findByUsername(userVO.getUsername());
        if (user != null && user.getPassword().equals(userVO.getPassword())) {
            session.setAttribute("user", user);
            userMapper.updateLastLoginTime(new Timestamp(System.currentTimeMillis()), user.getId());
            map.put("code", 200);
            map.put("msg", "登陆成功！");
            map.put("data", user);
        }
        else{
            map.put("code", 500);
            map.put("msg", "用户名或者密码错误！");
        }
        return map;
    }

    public Map<String, Object> codeLogin(String phone, String inputCode, HttpSession session)  {
        Map<String, Object> map = new HashMap<>();
        User user = userMapper.findByPhone(phone);
        long currentTime = System.currentTimeMillis();
        long time = currentTime - 5*60*1000;
        if (user != null && user.getSendCode() != null && user.getSendTime() != null && time < user.getSendTime() && user.getSendCode().equals(inputCode)) {
            session.setAttribute("user", user);
            userMapper.updateLastLoginTime(new Timestamp(System.currentTimeMillis()), user.getId());
            map.put("code", 200);
            map.put("msg", "登陆成功！");
            map.put("data", user);
            userMapper.updateCodeById(user.getId());
            System.out.println("codeLogin+++++++++++++if");
        }
        else{
            map.put("code", 500);
            map.put("msg", "验证码错误或已超时！");
        }
        System.out.println("codeLogin----------------end");
        System.out.println(map);
        return map;
    }

    public Map<String, Object> sendCode(String phone){
        Map<String, Object> map = new HashMap<>();
        if(userMapper.findByPhone(phone) == null){
            map.put("code", 500);
            map.put("msg", "该手机号不存在！");
            return map;
        }
        if(userMapper.findByPhone(phone).getSendTime() !=null && System.currentTimeMillis() - userMapper.findByPhone(phone).getSendTime() < 60){
            map.put("msg", "验证码已发送，请稍后再试！");
            return map;
        }

        int sendCode = (int)((Math.random() * 9 + 1) * 1000);

        String host = "https://intlsms.market.alicloudapi.com";
        String path = "/comms/sms/sendmsgall";
        String method = "POST";
        String appcode = "b0ab85a6b9f146259bb133d7735281ac";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("callbackUrl", "http://test.dev.esandcloud.com");
        bodys.put("channel", "0");
        bodys.put("mobile", "+86" + phone);
        bodys.put("templateID", "0000000");
        bodys.put("templateParamSet", sendCode + ", 5");


        map.put("code", 500);
        map.put("msg", "发送失败！");
        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
            String s = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = new JSONObject(s);
            String code = jsonObject.getString("code");
            if ("0000".equals(code)){
                map.put("code", 200);
                map.put("msg", "验证码已发送！");
                long sendTime = System.currentTimeMillis();
                userMapper.updateByPhone(phone, "" + sendCode, sendTime);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
